package com.onemore.task;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class AutoClean {
	/**
     * @param args
     */
    public void run(int retainDay) {    
         String path = "./logs";//args[0];
         List<File> list = getFileSort(path);
         for (int i = list.size()-1; i >= 0; i--) {
        	File file = list.get(i);
        	String fileTime = regMatch(file.getName(), "[^\\.]\\.(\\d+)\\.log");
        	if(fileTime != null) {
            	long fileStamp;
				try {
					fileStamp = dateToStamp(fileTime);
	                if(getDayPoor(new Date(),new Date(fileStamp)) > retainDay){
	                	file.delete();
	                }
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}//Integer.valueOf(fileTime);
        	}
 		}
         /*for (File file : list) {
             System.out.println(file.getName() + " : " + file.lastModified());
             System.out.println(regMatch(file.getName(), "[^\\.]\\.(\\d+)\\.log"));
         }*/

     }
    public static int getDayPoor(Date endDate, Date nowDate) {
   	 
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
//        long hour = diff % nd / nh;
        // 计算差多少分钟
//        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return (int) day;
    }
    public static String getDatePoor(Date endDate, Date nowDate) {
    	 
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
      public static String regMatch(String withinText, String regString) {
          String code = null;
          Pattern pattern = Pattern.compile(regString);
          Matcher matcher = pattern.matcher(withinText);
          if (matcher.find()) {
              matcher.reset();
              while (matcher.find()) {
                  /*code = matcher.group(1);
                  System.err.println("aaaa" + code);
                  code = matcher.group(0);
                  System.err.println("bbbb" + code);
                  code = matcher.group(2);
                  System.err.println("ccc" + code);*/
            	  code = matcher.group(1);
              }
          }
          return code;
      }
	/**
     * 将时间转换为时间戳
     */    
    public static long dateToStamp(String s) throws ParseException{
        String res;
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = simpleDateFormat.parse(s);
        return date.getTime();
//        res = String.valueOf(ts);
//        return res;
    }
    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    /**
     * 获取目录下所有文件(按时间排序)
     * 
     * @param path
     * @return
     */
    public static List<File> getFileSort(String path) {
 
        List<File> list = getFiles(path, new ArrayList<File>());
 
        if (list != null && list.size() > 0) {
 
            Collections.sort(list, new Comparator<File>() {
                public int compare(File file, File newFile) {
                    if (file.lastModified() < newFile.lastModified()) {
                        return 1;
                    } else if (file.lastModified() == newFile.lastModified()) {
                        return 0;
                    } else {
                        return -1;
                    }
 
                }
            });
 
        }
 
        return list;
    }
 
    /**
     * 
     * 获取目录下所有文件
     * 
     * @param realpath
     * @param files
     * @return
     */
    public static List<File> getFiles(String realpath, List<File> files) {
        File realFile = new File(realpath);
        if (realFile.isDirectory()) {
            File[] subfiles = realFile.listFiles();
            for (File file : subfiles) {
                if (file.isDirectory()) {
                    getFiles(file.getAbsolutePath(), files);
                } else {
                    files.add(file);
                }
            }
        }
        return files;
    }
}

